package edu.towson.cosc.cosc490.lab7;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class MapLocation extends Activity {


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		final EditText addrText = (EditText) findViewById(R.id.location);
		final Button button = (Button) findViewById(R.id.mapButton);
		final Button buttonCurrentLocation = (Button) findViewById(R.id.buttonCurrentLocation);
		final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

		// When the Show Map button is clicked, fire an intent showing a map of the search item
		button.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				try {
					String address = addrText.getText().toString();
					address = address.replace(' ', '+');
					Intent geoIntent = new Intent(
							android.content.Intent.ACTION_VIEW, Uri
									.parse("geo:0, 0?q=" + address));
					startActivity(geoIntent);
				} catch (Exception e) {
				}
			}
		});
		
		buttonCurrentLocation.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v){
				try{
					Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
					Intent currentLocationIntent = new Intent(android.content.Intent.ACTION_VIEW, 
							Uri.parse("geo:" +location.getLatitude()+","+location.getLongitude()+"?z=18"));
					startActivity(currentLocationIntent);
				}catch(Exception e){

				}
			}
		});
	}
	
	public void onStart(){
		super.onStart();
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	    final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	    if (!gpsEnabled) {
	    	AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
	    	dialogBuilder.setTitle("GPS is Not Enabled");
	    	dialogBuilder
	    	.setMessage("Open GPS settings?")
	    	.setCancelable(true)
	    	.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
	    		public void onClick(DialogInterface dialog, int id){
	    			Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	    		    startActivity(settingsIntent);
	    		}
	    	})
	    	.setNegativeButton("No", new DialogInterface.OnClickListener(){
	    		public void onClick(DialogInterface dialog, int id){
	    			dialog.cancel();
	    		}
	    	});
	    	AlertDialog alertDialog = dialogBuilder.create();
	    	alertDialog.show();
	    }
	}
}
